# Contents: File_Manager Module for handling Loading and Saving of the XML Library
# Purpose:
# Status:

require 'rubygems'
begin
require 'xml/libxml' #use this line on linux instead.  There's some quirks in the libxml implementation
rescue LoadError
require 'xml/libxml_so' #use this for windows
end

include XML #namespace hack

module File_Manager
	def File_Manager.load_file (filename)
		lib = Array.new
    
    #lib=Hash.new
					
		rDoc = Document.file(filename)
		rRoot = rDoc.root
		      
		rDoc.find('//musink/library/track').each do |node| #find each track in the xml database
			#create a new song object
			
			asong = Song.new( node.find_first('filepath').content,
									node.find_first('artist').content,
									node.find_first('album').content,
									node.find_first('title').content,
									node.find_first('duration').content,
									node.find_first('hash').content,
									node.find_first('playcount').content,
									node.find_first('rating').content,
									node.find_first('last_played').content)
								
			#adds song to library
			#Hash.store(asong.hash,asong);
      lib<<asong
		end
		return lib
	end
	
	def File_Manager.save_file (my_library, filename)
		#print "File_Manager / Save"
		doc = XML::Document.new
		doc.root = XML::Node.new('musink')	#setup root node
		root = doc.root
		root<<generation_date = Node.new("generation_date")
		generation_date << Time.new.strftime("%Y%m%d %H:%M:%S")
		root<<library = Node.new("library")

		my_library.each do |s|   #k = hash, s = song object
			#setup all the track data for the XML Node				
			library<<track = Node.new("track")
			track<<filepath = Node.new("filepath")
			track<<artist = Node.new("artist")
			track<<album = Node.new("album")
			track<<title = Node.new("title")
			track<<duration = Node.new("duration") 
			track<<hash = Node.new("hash") 
			track<<playcount = Node.new("playcount") 
			track<<rating = Node.new("rating")
			track<<last_played = Node.new("last_played") 

			#push all the data into the Node
			filepath << s.filepath
			artist << s.artist
			album << s.album
			title << s.title
			duration << s.duration
			hash << s.hash
			playcount << s.playcount
			rating << s.rating
			last_played << s.last_played				
		end

		format = true
		doc.save(filename, format)
	end
end
